import requests
import unittest
import setup_common
import csv
import os

class AsnTest(unittest.TestCase):
    def setUp(self):
        self.ip = setup_common.get_shared_ip()
        self.asnpreviewurl = setup_common.generate_url(self.ip, "asn/viewprint")
        self.asnurl = setup_common.generate_url(self.ip,"asn/list")
        self.confirm_url = setup_common.generate_url(self.ip, "asn/preload")
        self.headers = setup_common.get_shared_headers()
        self.asn_list = []

    def get_asn_list(self):
        # 测试逻辑1-生成所有的到货通知书列表，并作为测试用例的输入条件
        all_asn_id = []
        asn_code = []
        page = 1
        while True:
            response = requests.get(url=self.asnurl, headers=self.headers, params={"page": page})
            data = response.json()
            asn_res = data.get('results', [])
            if not asn_res:
                break
            self.asn_list.extend(asn_res)
            asn_ids = [item['id'] for item in asn_res]
            asn_codes = [item['asn_code'] for item in asn_res]
            all_asn_id.extend(asn_ids)
            asn_code.extend(asn_codes)
            page += 1
        return all_asn_id, asn_code, self.asn_list

    def test_get_asn_list(self):
        # get_asn_list方法作为测试用例的输入，生成此脚本重要的测试用例
        all_asn_id, asn_code, asn_list = self.get_asn_list()
        csv_filename = "asn_list.csv"
        with open(csv_filename, mode='w', newline='', encoding='utf-8') as file:
            fieldnames = ['id', 'asn_code', 'asn_status', 'supplier']
            writer = csv.DictWriter(file, fieldnames=fieldnames)
            writer.writeheader()
            for item in asn_list:
                writer.writerow({field: item.get(field, '') for field in fieldnames})

    def test_post_asn_confirm(self):
        # 测试逻辑2-以测试用例中的asn_status=1作为输入，预期结果为asn_status=2
        csv_filename = "asn_list.csv"
        if not os.path.exists(csv_filename):
            print(f"File '{csv_filename}' not found. Generating it now...")
            self.test_get_asn_list()

        # 无论文件是否存在，都进行文件读取和处理逻辑
        try:
            with open(csv_filename, mode='r', newline='', encoding='utf-8') as file:
                fieldnames = ['id', 'asn_code', 'asn_status', 'supplier']
                reader = csv.DictReader(file, fieldnames=fieldnames)
                rows_to_assert = []  # 存储符合条件的行
                first_iteration = True
                for row in reader:
                    if first_iteration:
                        first_iteration = False
                        continue  # 跳过第一次迭代
                    asn_status = row['asn_status']
                    if asn_status == '1':  # 只处理 asn_status 为 1 的行
                        id_value = row['id']
                        asn_confirm_url = f"{self.confirm_url}{id_value}/"
                        response = requests.request("POST", url=asn_confirm_url, headers=self.headers).text
                        print(asn_confirm_url)
                        print(response)
                        print(row)
                        row['asn_status'] = '2'  # 将状态修改为 '2'
                        rows_to_assert.append(row)  # 添加符合条件的行
                return rows_to_assert  # 返回符合条件的所有行
        except FileNotFoundError:
            print(f"File '{csv_filename}' 未找到，文件生成失败")

    def test_asn_confirm(self):
        rows_to_assert = self.test_post_asn_confirm()

        for row in rows_to_assert:
            expected_status = '2'
            actual_status = row['asn_status']
            id_value = row['id']

            assert actual_status == expected_status, f"ID: {id_value}，预期值: {expected_status}，实际值: {actual_status}，断言失败"




if __name__ == '__main__':
    unittest.main()
